package agu.misc;

import java.lang.reflect.Array;
import java.util.List;
import androidx.arch.core.util.Function;

public class ArrayUtil
{

    @SuppressWarnings("unchecked")
    public static <T> T[] toArray(List<T> list){
        Class<?> type;
        try{
            type = list.get(0).getClass();
        }catch(Exception ex){
            type = Object.class;
        }
        return (T[])toArray(list, type, null);
    }

    @SuppressWarnings("unchecked")
    public static <T, I> T[] toArray(List<I> list, Class<T> type, Function<I, T> transformer){
        int size = list == null? 0: list.size();

        T[] array = (T[])Array.newInstance(type, size);

        for(int i = 0; i < size; i++){
            I item = list.get(i);
            if(transformer == null){
                array[i] = (T)item;
                continue;
            }
            array[i] = transformer.apply(item);
        }

        return array;
    }

    public static <T> T reverseArray(T array){
        int length = Array.getLength(array);
        for(int i = 0; i < length; i++){
            int j = length - 1 - i;
            if(i >= j) break;
            Object item = Array.get(array, i);
            Array.set(array, i, Array.get(array, j));
            Array.set(array, j, item);
        }
        return array;
    }

}
